
#include "../crypt/CryptEChain.h"
#include "../net/Broker4.h"
#include "../utils/BaseConvert.h"
#include "Broker4.h"
#include "Broker4Client.h"

int Broker4Client::MessageExchange(EncMessage *msg, KeyDB *kdb)
{
   int retval = SendMessage(msg, kdb);
   msg->Reset();
   if (retval == 1) return 1;
   RecvMessage(msg, kdb);
   return 0;
}

int Broker4Client::SendMessage(EncMessage *msg, KeyDB *kdb)
{
   // return 1 for failure
   if (!isvalid) { errprint("network problem"); return 1; }
   APRBucketBrigade *aprbb = new APRBucketBrigade(mp);
   int success = (Broker4::WriteEncMessageToBB(aprbb, msg, kdb) == 0);
   if (success)
   {
      aprbb->WriteEOS();
      apr_size_t rlen = aprbb->RealLength();
      apr_size_t sentbytes = SendBucketBrigade(aprbb);
      int retval = (sentbytes != rlen);
      if (retval)
         errprint("expected to send %d bytes, actually sent %d\n", sentbytes, rlen);
      delete aprbb;
      return retval;
   } else
   {
      errprint("Sending message did not succeed");
      delete aprbb;
      return 1;
   }
}

int Broker4Client::RecvMessage(EncMessage *msg, KeyDB *kdb)
{
   int success = (Broker4::ReadEncMessageFromBB(clientbb, msg, kdb, NULL) == 0);
   if (success)
   {
      // Divine meaning from the EMessage msg!
   }
   return 0;
}
